package ws.jdbc.concurrent.test.tasks;

import java.sql.SQLException;
import ws.jdbc.concurrent.statement.IStatement;

/**
 * This runnable tries execute an SQL batch on the concurrent statement {@link IStatement}.
 *
 * @author Wilson Santos, 36228 <wilson.santos@ua.pt>
 */
public class EStatementRunnable implements Runnable {

  /** Statement of run the batch. */
  private static IStatement stmt;
  /** Thread cycle count. */
  private static int cycleCount;
  /** Value to update col1. */
  private int num = 34;
  /** Values to update col2 and col3. */
  private String str1 = "d2", str2 = "d3";
  /** Value to update col4. */
  private float decimal = 9.1f;

  public EStatementRunnable() {
  }

  /** Set the statement to run the batch. */
  public static void setIStatement(IStatement stmt) {
    assert stmt != null;
    EStatementRunnable.stmt = stmt;
  }

  /**
   * Set Thread cycle count.
   *
   * @param cycleCount Thread cycle count.
   */
  public static void setCycleCount(int cycleCount) {
    assert cycleCount > 0;
    EStatementRunnable.cycleCount = cycleCount;
  }
  
  /**
   * Add several SQL commands to the statement object and them run them.
   */
  public void run() {
    try {
      for (int i = 0; i < cycleCount; i++) {
        stmt.addBatch("UPDATE TestData SET col1=" + num);
        stmt.addBatch("UPDATE TestData SET col2='" + str1 + "'");
        stmt.addBatch("UPDATE TestData SET col3='" + str2 + "'");
        stmt.addBatch("UPDATE TestData SET col4=" + decimal);
      }
      stmt.executeBatch();
    } catch (SQLException ex) {
      ex.printStackTrace();
    }
  }
}
